<?php
//封装增删改查方法
//使用实例：
/*直接复制这一段：
include"./funcs.php";
$link=conn();
$arr=select($link,'users');
echo "<pre>";
print_r($arr);
echo "</pre>";
*/
//连接
function conn($host="127.0.0.1",$user="root",$pwd="lisong",$db="fenxiao",$char="utf8"){
	$link = mysqli_connect($host,$user,$pwd);
	mysqli_select_db($link,$db);
	mysqli_set_charset($link,$char);
	return $link;
}
//查询
function select($link,$tableName,$where="",$cols="*",$limit=""){
	if($where!=""){
		$where="where ".$where;
	}
	if($limit!=""){
		$limit="limit ".$limit;
	}
	$sql="select $cols from $tableName $where $limit";
	$re=mysqli_query($link,$sql);
	if($re==FALSE){
		echo "sql拼写有误！！";
		echo $sql;
	}else{
		// echo $sql;
		$arr=array();
		while($row=mysqli_fetch_assoc($re)){
			$arr[]=$row;
		}
		if(empty($arr)){
			//echo "没有符合条件的记录";
		}else{
			return $arr;
		}
	}
}


//修改
function save($link,$tableName,$arr,$where=""){
	if($where!=""){
		$where="where ".$where;
	}
	foreach($arr as $k=>$v){
		$str .=$k.'='."'".$v."'".",";
	}
	$str=trim($str,",");
	$sql="update $tableName set $str $where";
	$re=mysqli_query($link,$sql);
	if($re>0){
		return TRUE;
	}else{
		return FALSE;
	}
}
//添加
function add($link,$tableName,$arr){
	$keys=array_keys($arr);
	$keys=join(",", $keys);
	$values=array_values($arr);
	$values="'".join("','",$values)."'";
	$sql="insert into $tableName ($keys) values ($values)";
	echo $sql;
	$re=mysqli_query($link,$sql);
	if($re>0){
		return TRUE;	
	}else{
		return FALSE;
	}
}
//删除
function del($link,$tableName,$where=""){
	if($where!=""){
		$where="where ".$where;
	}
	$sql="delete from $tableName $where";
	$re=mysqli_query($link,$sql);
	if($re>0){
		return true;
	}else{
		return FALSE;
	}
}
//执行所有sql
function query($link,$sql){
	$re=mysqli_query($link,$sql);
	if(is_object($re)){
		$arr=array();
		while($row=mysqli_fetch_assoc($re)){
			$arr[]=$row;
		}
		if(empty($arr)){
			echo "暂无记录！！";
		}else{
			return $arr;
		}
	}else{
		if($re>0){
			return TRUE;
		}else{
			return FALSE;
		}
	}
}
//分页
function limit($link,$tableName,$page="1",$pagesize="10"){
	$star=($page-1)*$pagesize;
	$sql = "select * from $tableName limit $star,$pagesize"; 
	echo $sql;
	$re= mysqli_query($link,$sql);
	if($re){
		$arr=array();
		while($row=mysqli_fetch_assoc($re)){
			$arr[]=$row;
		}
		return $arr;
	}else{
		echo "sql 拼写有误！";
	}	
}
?>